package com.example.demo.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.example.demo.entity.Users;
import com.example.demo.mapper.UsersMapper;
import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

@Service
public class SecurityUserDetail implements UserDetailsService {

    private static Logger logger = LoggerFactory.getLogger(SecurityUserDetail.class);
//    @Override
//    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        // 生成一个包含账号密码的认证信息
//        // Authentication authenticationToken = new UsernamePasswordAuthenticationToken(username, passwrod);
//        // AuthenticationManager校验这个认证信息，返回一个已认证的Authentication
//        // Authentication authentication = authenticationManager.authenticate(authenticationToken);
//        // 将返回的Authentication存到上下文中
//        // SecurityContextHolder.getContext().setAuthentication(authentication);
//        System.out.println("loadUser---" + username);
//        // 模拟从数据库中加载用户信息
//        // 后面章节将详细介绍如何从数据中加载数据
//        if ("user".equals(username)) {
//           List<GrantedAuthority> authorities = new ArrayList<>();
//           authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
//
//           String password = new BCryptPasswordEncoder().encode("123456");
//           return new User(username, password, authorities);
//        }
//        throw new UsernameNotFoundException("<notFound>");
//    }
//@Autowired
//private UserRepository userRepository;
//    private UsersServiceImpl userServiceImpl;

    @Resource
    private UsersMapper usersMapper;
    @Autowired
    private ObjectMapper objectMapper;

//    @Resource
//    private final UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("<UNK>" + username);
        // 这里应该从数据库中获取用户信息
        // 为了简化示例，我们创建一个模拟用户
//        User user = new User();
//        Optional<User> optionalUser = user;
//
//        Optional
//        return optionalUser.orElseThrow(() ->
//                new UsernameNotFoundException("User not found with username: " + username)
//        );

        //  List<GrantedAuthority> authorities = new ArrayList<>();
        //  authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        //  String password = new BCryptPasswordEncoder().encode("123456");
        //  return new User(username, password, authorities);
         // 从数据库中获取用户信息
         System.out.println("usersMapper");
         System.out.println(username);

//         try {
//            usersMapper.getUserOne(username);
//         } catch (Exception e) {
//             System.out.println(e.getMessage());
//             e.printStackTrace();
//         }
         Users user = usersMapper.getUserOne(username);
        logger.warn("JSON处理异常", "测试logger");


        try {
            System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
        } catch (JsonProcessingException e) {
            logger.warn("JSON处理异常", e);
            throw new RuntimeException(e);
        }

//         System.out.println(objectMapper.activateDefaultTyping());
        // try {
        //     System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
        // } catch (JsonProcessingException e) {
        //     throw new RuntimeException(e);
        // }

        System.out.println("<UNK> end");
         if (user == null) {
             throw new UsernameNotFoundException("User not found with username: " + username);
         }
         user.setRoles(new ArrayList<>());
         return user;

//          List<GrantedAuthority> authorities = new ArrayList<>();
//          authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
//          String password = new BCryptPasswordEncoder().encode("123456");
//          return new Users(user.getUsername(), user.getPassword());
    }

}
